package com.gomyb.admin.core.shiro.util;

import com.gomyb.common.utils.SpringContextUtil;
import com.gomyb.redis.RedisService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.Subject;

import java.util.Set;

/**
 * @author <a href="mailto:hellohesir@gmail.com">Mr_He</a>
 */
public class ShiroUtil {

    public static final String SHIRO_CACHE_PREFIX = "shiro:function:";

    private static RedisService redisService = SpringContextUtil.getBean("redisService");

    /**
     * 获得当前用户所有权限url
     */
    public static Set<String> getPermissions() {
        Subject subject = SecurityUtils.getSubject();
        if (null != subject) {
            Object username = subject.getPrincipal();
            SimpleAuthorizationInfo simpleAuthorizationInfo = redisService.getObj(SHIRO_CACHE_PREFIX + username);
            if (null != simpleAuthorizationInfo) {
                return simpleAuthorizationInfo.getStringPermissions();
            }
        }
        return null;
    }

    /**
     * 获得当前用户所有角色
     */
    public static Set<String> getRoles() {
        Subject subject = SecurityUtils.getSubject();
        if (null != subject) {
            Object username = subject.getPrincipal();
            SimpleAuthorizationInfo simpleAuthorizationInfo = redisService.getObj(SHIRO_CACHE_PREFIX + username);
            if (null != simpleAuthorizationInfo) {
                return simpleAuthorizationInfo.getRoles();
            }
        }
        return null;
    }

    /**
     * 获得用户名
     */
    public static String getUsername() {
        Subject userName = SecurityUtils.getSubject();
        if (null != userName) {
            return userName.toString();
        }
        throw new RuntimeException("no login...");
    }

}
